package algorithm.leetcode.simple;

/*
 给定一个二叉树，判断它是否是高度平衡的二叉树。
 */

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/10/12
 */
public class Question110 {
    public static void main(String[] args) {

    }

    public boolean isBalanced(TreeNode root) {
        return height(root) >= 0;
    }

    /**
     * 递归 自底向上
     */
    private int height(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = height(root.left);
        int rightHeight = height(root.right);
        if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
            // 其中左子树或者右子树不是平衡二叉树
            return -1;
        }
        return Math.max(leftHeight, rightHeight) + 1;
    }


    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
